<template>
  <div class="mpb-wrapper">
    <div v-if="childIndex > 0" class="currentPath">
      {{echartOption[sectionType].title}} >
      <span v-if="path1">{{path1}}</span>
      <span v-if="path2">>{{path2}}</span>
    </div>
    <div class="mpb-time-select">
      <div :class="{'current': dateType === 2}" @click="changeTimeType(2)">周报</div>
      <div :class="{'current': dateType === 3}" @click="changeTimeType(3)">月报</div>
      <div :class="{'current': dateType === 4}" @click="changeTimeType(4)">季报</div>
    </div>
    <div class="block">
      <el-slider
        v-model="value"
        show-stops
        :format-tooltip="formatTooltip"
        :min="1"
        @change="getData"
        :max="maxLength">
      </el-slider>
    </div>
    <div>
      <div ref="echart1" class="echart-class"></div>
      <p class="total">{{totalTimeRange}} 整体业绩：{{total.totalSale}}</p>
      <div ref="echart2" class="echart-class"></div>
    </div>
    <div v-if="childIndex === 0" class="component-tabbar" :style="{'paddingBottom': bottomBarHeight + 'px'}">
      <div class="tab" @click="changeTab('yjhz')">
        <p :class="{'active': sectionType === 'yjhz'}">业绩汇总</p>
      </div>
      <div class="tab" @click="changeTab('flsc')">
        <p :class="{'active': sectionType === 'flsc'}">分类市场</p>
      </div>
      <div class="tab" @click="changeTab('ptyy')">
        <p :class="{'active': sectionType === 'ptyy'}">平台运营</p>
      </div>
      <div class="tab" @click="changeTab('tdcg')">
        <p :class="{'active': sectionType === 'tdcg'}">团队成果</p>
      </div>
    </div>
  </div>
</template>

<script>
  import {dateUtil} from '@/utils/dateUtil'
  import dingMixin from  '@/mixins/ding'

  export default {
    data () {
      return {
        value: 6,
        chart1: null,
        chart2: null,
        total: {
          totalSale: 0
        },
        totalTimeRange: '',
        dateType: 2,
        monthSelect: [],
        maxLength: 12,
        bottomBarHeight: 0,
        quarterSelect: [],
        sectionType: 'yjhz',
        echartOption: {
          yjhz: {
            title: '业绩汇总',
            hasNext: false,
            url: 'mpb/report/summary',
            pieData: [{name: '市场业绩', value:'marketSale'},{name: '市场广告', value:'marketAd'},{name: '平台业绩', value:'platSale'},{name: '平台广告', value:'platAd'}],
            lineData: [{name: '整体业绩', value:'totalSale'},{name: '市场业绩', value:'marketSale'},{name: '市场广告', value:'marketAd'},{name: '平台业绩', value:'platSale'},{name: '平台广告', value:'platAd'}]
          },
          flsc: {
            title: '分类市场',
            url: 'mpb/report/market_app',
            hasNext: true,
          },
          ptyy: {
            title: '平台运营',
            url: 'mpb/report/plat_app',
            hasNext: true,
          },
          tdcg: {
            title: '团队成果',
            url: 'mpb/report/team_app2',
            hasNext: true,
          }
        },
        childIndex: 0,
        path1: '',
        path2: '',
        routeParam: {}
      }
    },
    components: {
    },
    mixins: [dateUtil, dingMixin],
    async mounted(){
      if(this.$route.name === 'mmpb-detail' && !this.$route.params.type){
        this.routeParam =  JSON.parse(sessionStorage.getItem('mmpbstorage'));
      }
      this.sectionType = this.$route.meta.type || this.$route.params.type || this.routeParam.type;
      this.childIndex = this.$route.params.childIndex || this.routeParam.childIndex ||  0;
      this.path1 = this.$route.params.path1 || this.routeParam.path1 || '';
      this.path2 = this.$route.params.path2 || this.routeParam.path2 ||  '';

      if(this.childIndex === 1 && this.$route.params.type) {
        sessionStorage.setItem('mmpbstorage', JSON.stringify(this.$route.params))
      }
      this.mobileGetDevice(({model, brand, version}) => {
        if(brand === 'iPhone' && ( model.indexOf('10') > 0 || model.indexOf('11') > 0)) {
          this.bottomBarHeight = 15;
        }
      })
      this.getData(this.value)
      this.initMonthSelect()
      this.initQuarterSelect()
    },
    methods: {
      initMonthSelect() {
        let date = dateUtil.thisMonth().split('-');
        for(let i = 0; i< 12; i++ ){
          if((parseInt(date[1]) - i) >=1){
            this.monthSelect.push(`${date[0]}-${('0' + (date[1] - i)).substr(-2)}`)
          }else{
            this.monthSelect.push(`${parseInt(date[0]) - 1}-${('0' + (date[1] - i + 12)).substr(-2)}`)
          }
        }
      },
      changeTab(tab) {
        this.$router.push({ name: 'mmpb-' + tab})
      },
      initQuarterSelect() {
        let date = dateUtil.thisMonth().split('-');
        if(parseInt(date[1]) <=3 ) {
          this.quarterSelect.push(`${parseInt(date[0])}.01-${parseInt(date[0])}.03`
          , `${parseInt(date[0]) - 1}.10-${date[0] - 1}.12`
          , `${parseInt(date[0]) -1}.07-${parseInt(date[0]) -1}.09`
          , `${parseInt(date[0])-1}.04-${parseInt(date[0])-1}.06`
          , `${parseInt(date[0]) -1}.01-${parseInt(date[0])}.03`
          , `${parseInt(date[0]) - 2}.10-${date[0] - 2}.12`
          , `${parseInt(date[0]) -2}.07-${parseInt(date[0]) -2}.09`
          , `${parseInt(date[0])-2}.04-${parseInt(date[0]) -2}.06`)
        }else if(parseInt(date[1]) >3 && parseInt(date[1]) <=6) {
          this.quarterSelect.push(`${parseInt(date[0])}.04-${parseInt(date[0])}.06`
          ,`${parseInt(date[0])}.01-${parseInt(date[0])}.03`
          , `${parseInt(date[0]) - 1}.10-${date[0] - 1}.12`
          , `${parseInt(date[0]) -1}.07-${parseInt(date[0]) -1}.09`
          , `${parseInt(date[0])-1}.04-${parseInt(date[0])-1}.06`
          , `${parseInt(date[0]) -1}.01-${parseInt(date[0])}.03`
          , `${parseInt(date[0]) - 2}.10-${date[0] - 2}.12`
          , `${parseInt(date[0]) -2}.07-${parseInt(date[0]) -2}.09`)
        }else if(parseInt(date[1]) >6 && parseInt(date[1]) <= 9) {
          this.quarterSelect.push(`${parseInt(date[0])}.06-${parseInt(date[0])}.09`
          , `${parseInt(date[0])}.04-${parseInt(date[0])}.06`
          , `${parseInt(date[0])}.01-${parseInt(date[0])}.03`
          , `${parseInt(date[0]) - 1}.10-${date[0] - 1}.12`
          , `${parseInt(date[0]) -1}.07-${parseInt(date[0]) -1}.09`
          , `${parseInt(date[0])-1}.04-${parseInt(date[0])-1}.06`
          , `${parseInt(date[0]) -1}.01-${parseInt(date[0])}.03`
          , `${parseInt(date[0]) - 2}.10-${date[0] - 2}.12`)
        }else if(parseInt(date[1]) >9) {
          this.quarterSelect.push(`${parseInt(date[0])}.10-${parseInt(date[0])}.12`
          , `${parseInt(date[0])}.06-${parseInt(date[0])}.09`
          , `${parseInt(date[0])}.04-${parseInt(date[0])}.06`
          , `${parseInt(date[0])}.01-${parseInt(date[0])}.03`
          , `${parseInt(date[0]) - 1}.10-${date[0] - 1}.12`
          , `${parseInt(date[0]) -1}.07-${parseInt(date[0]) -1}.09`
          , `${parseInt(date[0])-1}.04-${parseInt(date[0])-1}.06`
          , `${parseInt(date[0]) -1}.01-${parseInt(date[0])}.03`)
        }
      },
      changeTimeType(type) {
        this.dateType = type;
        if(type === 4) {
          this.maxLength = 8;
          this.value = 4;
        }else {
          this.maxLength = 12;
          this.value = 6;
        }
        this.getData(this.value)
      },
      formatTooltip(val) {
        return `最近${val}${this.dateType === 2 ? '周': this.dateType === 4 ? '季度':'月'}`;
      },
      async getData(val) {
        let to;
        let from
        if(this.dateType === 2) {
          from = dateUtil.nDaysBefore(7*(val - 1));
          to = dateUtil.thisDay();
        }else if(this.dateType === 3) {
          from = this.monthSelect[val-1];
          to = this.monthSelect[0]
        }else if(this.dateType === 4) {
          from = this.quarterSelect[val-1];
          to = this.quarterSelect[0]
        }

        let postParam = {
          from,
          to,
          dateType: this.dateType
        }

        if(this.sectionType === 'flsc') {
          postParam.levelId = this.$route.params.id1 || this.routeParam.id1 || '';
          postParam.countryCode = this.$route.params.id2 || this.routeParam.id2 || '';
        }else if(this.sectionType === 'tdcg') {
          postParam.teamId = this.$route.params.id1 || this.routeParam.id1 || '';
          postParam.countryCode = this.$route.params.id2 || this.routeParam.id2 || '';
        }else if(this.sectionType === 'ptyy') {
          if(this.childIndex === 1) postParam.platId = this.$route.params.id1 || this.routeParam.id1 || '';
          if(this.childIndex === 2) postParam.platId = this.$route.params.id2 || this.routeParam.id2 || '';
        }

        let data = await this.$httpN.postB(this.echartOption[this.sectionType].url, postParam)

        if(this.sectionType === 'yjhz') {
          this.total = data[data.length - 1];
          if(this.dateType === 2) {
            if(this.value > 1) {
              this.totalTimeRange = `${data[0].date.split('到')[0]} 到 ${data[data.length - 2].date.split('到')[1]}`
            }else{
              this.totalTimeRange = `${data[0].date}`
            }
          }else{
            if(this.value > 1) {
              this.totalTimeRange = `${data[0].date} 到 ${data[data.length - 2].date}`
            }else{
              this.totalTimeRange = `${data[0].date}`
            }
          }
        }else{
          if(this.dateType === 2) {
            if(this.value > 1) {
              this.totalTimeRange = `${data.dates[0].split('到')[0]} 到 ${data.dates[data.dates.length - 1].split('到')[1]}`
            }else{
              this.totalTimeRange = `${data.dates[0]}`
            }
          }else{
            if(this.value > 1) {
              this.totalTimeRange = `${data.dates[0]} 到 ${data.dates[data.dates.length - 1]}`
            }else{
              this.totalTimeRange = `${data.dates[0]}`
            }
          }
        }
        this.setPieData(data)
        this.setLineData(data)
      },
      setPieData(data) {
        let that = this;
        if(!this.chart1) this.chart1 = echarts.init(this.$refs.echart1);
        let pieData = [];
        if(this.sectionType === 'yjhz') {
          this.echartOption[this.sectionType].pieData.forEach(item => {
            pieData.push({name: item.name, value: this.total[item.value]})
          })
        }else{
          let traverseObj = data.ids === ''? data.values: data.ids
          for(let key in traverseObj) {
            if(data.values[key]) {
              let sum = data.values[key].reduce((prev, curr) => prev + curr);
              if(sum > 0 && key !== '整体业绩') {
                pieData.push({name: key, value: sum})
              }
            }
          }
          this.total.totalSale = data.total;
        }
        window.copyText = (name)=> {
          if(this.childIndex === 0) {
            that.$router.push({name: 'mmpb-detail', params: {type: this.sectionType, id1: data.ids[name], childIndex: this.childIndex + 1, path1: name}})
          }else if(this.childIndex === 1) {
            that.$router.push({name: 'mmpb-deepDetail', params: {type: this.sectionType, id1: this.$route.params.id1 || this.routeParam.id1, id2: data.ids[name], childIndex: this.childIndex + 2, path1: this.path1, path2: name}})
          }
        }
        this.chart1.setOption({
          title: {
            text: this.childIndex === 0 ? that.echartOption[that.sectionType].title : this.childIndex === 1 ? this.$route.params.path1 || this.routeParam.path1: this.$route.params.path2 || this.routeParam.path2,
            left: 'left',
            textStyle: {
              fontWeight: 'normal',
              fontSize: 14
            }
          },
          tooltip: {
            trigger: 'item',
            confine: true,
            enterable: true,
            formatter: (params) => {
              if(((that.sectionType === 'flsc' || that.sectionType === 'tdcg') && that.childIndex < 2) || ((that.sectionType === 'ptyy') && that.childIndex < 1)) {
                return `<span>${params.name}:${params.value}(${params.percent}%)</span><br><span onclick="copyText('${params.name}')">查看详情></span>`
              }else {
                return `<span>${params.name}:${params.value}(${params.percent}%)</span>`
              }
            },
          },
          series: [{
            type: 'pie',
            radius: '65%',
            center: ['50%', '60%'],
            data: pieData,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            },
            label: {
            }
          }]
        })

        this.chart1.on('click', function (params) {
          that.chart2.dispatchAction({
            type: 'hideTip'
          });
        });

      },
      setLineData(data) {
        let that = this;
        if(!this.chart2) this.chart2 = echarts.init(this.$refs.echart2);
        let lineData = [];
        let legendData = [];
        let xAxisData = []

        if(this.sectionType === 'yjhz') {
          this.echartOption[this.sectionType].lineData.forEach(item => {
            lineData.push({name: item.name, type: 'line', data: []})
            legendData.push(item.name)
          })
          data.forEach(item => {
            if(item.date !== '总计') {
              this.echartOption[this.sectionType].lineData.forEach((option, index) => {
                lineData[index].data.push(item[option.value])
              })
              xAxisData.push(item.date)
            }
          })
        }else {
          let traverseObj = data.ids === ''? data.values: data.ids
          for(let key in traverseObj) {
            if(data.values[key]) {
              let sum = data.values[key].reduce((prev, curr) => prev + curr);
              if(sum >0) {
                lineData.push({name: key, type: 'line', data: data.values[key]})
                legendData.push(key)
              }
            }
          }
          xAxisData.push(...data.dates)
        }
      
        let interval = 0;
        if(this.dateType === 2 && this.value > 8) interval = 1; 
        if(this.dateType === 3 && this.value > 6) interval = 1; 

        let option2 = {
          tooltip: {
              trigger: 'axis'
          },
          legend: {
            data: legendData,
            type: lineData.length > 8 ? 'scroll': 'plain'
          },
          grid: {
              left: '3%',
              right: '4%',
              bottom: '3%',
              containLabel: true
          },
          xAxis: {
              type: 'category',
              boundaryGap: false,
              data: xAxisData,
              axisLabel:{
                align: 'center',
                interval: interval,
                fontSize: 12,
                formatter: function (value, index) {
                  if(that.dateType === 4) {
                    let result = value.replace('-', '');
                    return result.substr(-4);
                  }else if(that.dateType === 3) {
                    let result = value.replace(/月/g, '');
                    result = result.replace(/-/g, '.');
                    return result 
                  }else if(that.dateType === 2) {
                    let result = value.substr(-5);
                    result = result.split('-');
                    return `${parseInt(result[0])}.${parseInt(result[1])}`
                  }
                }
              }
          },
          yAxis: {
            type: 'value',
            axisLabel: {
              formatter: function (value, index) {
                if(value < 1000000) {
                  return value / 1000 + 'K'
                }else {
                  return value / 1000000 + 'M'
                }
              }
            }
          },
          series: lineData
        };
        this.chart2.clear();
        this.chart2.setOption(option2);
      }
    }
  }
</script>

<style lang="scss">
  .mpb-wrapper{
    min-height: 100vh;
    overflow:hidden;
    width: 100%;
    padding: 12px;
    .mpb-time-select{
      display: flex;
      >div{
        display: block;
        position: relative;
        -webkit-box-flex: 1;
        -webkit-flex: 1;
        flex: 1;
        width: 100%;
        height: 30px;
        padding: 0;
        font-size: 14px;
        line-height: 28px;
        text-align: center;
        color: #999;
        white-space: nowrap;
        background: #fdfdfd;
        -webkit-tap-highlight-color: rgba(255,0,0,0);
        border: 1px solid #ccc;
      }
      >div:first-child{
        border-top-left-radius: 32px;
        border-bottom-left-radius: 32px;
        border-right-width: 0;
      }
      >div:last-child{
        border-top-right-radius: 32px;
        border-bottom-right-radius: 32px;
        border-left-width: 0;
      }
      div.current{
        color: #000;
        background: #ffe26d;
      }
    }
    .total{
      text-align: center;
      margin: 30px 0;
    }
  }
  .echart-class{
    width: 100%;
    height: calc((100vh - 220px) / 2);
  }
  .component-tabbar{
    position:fixed;
    bottom:0;
    left: 0;
    width: 100%;
    text-align: center;
    background: #FFF;
    box-shadow: 0 0 10px 0 hsla(0,6%,58%,.6);
    z-index: 99;
    display: flex;
    .tab{
      flex: 1;
      line-height: 46px;
      p{
        margin: 0;
        color: #969696;
        &.active{
          color: #42A5F5;
        }
      }
    }
  }
  .currentPath{
    font-weight: bold;
    margin-bottom: 10px;
  }
</style>